package com.gxa.web_admin.controller.lyh;

import com.gxa.common.vo.R;
import com.gxa.common.vo.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

//import static com.sun.xml.internal.ws.spi.db.BindingContextFactory.LOGGER;

/**
 * Created with IntelliJ IDEA.
 * User: zls
 * Date: 2021/12/26 16:38:22
 * Description:
 * Version: V1.0
 */
@Controller
@Api(value = "问渐渐",tags = "上传文件数据接口API")
@RequestMapping("/file")
public class FileUploadController {

//    @RequestMapping("/pictureUpload")
    @ResponseBody
    public String saveUpload(MultipartFile multipartFile, HttpServletRequest request) {
        System.out.println(request.getParameter("name"));
        // 以当前日期创建一个文件夹，避免单个文件夹中文件过多
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        // 截取年月日：2020-11-02
        String substring = timestamp.toString().substring(0, 10);
        // 获取项目当前根路径
        String uploadPath = request.getServletContext().getRealPath("/" + substring);
        String savePosition = uploadPath + "static/pictureUpload/";
        System.out.println("当前根路径："+uploadPath);

        // 获取上传文件名字
        String uploadName = multipartFile.getOriginalFilename();
        System.out.println("原始文件名：" + uploadName);
        // 利用UUID生成新的图片名字，避免原图片被覆盖
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        // 截取上传文件的后缀
        String suffix = uploadName.substring(uploadName.lastIndexOf("."));
        // 拼接新的文件名字
        String newUploadName = uuid + suffix;
        System.out.println("新的文件名：" + newUploadName);

        String path = "D://javaTest//";
        File dir = new File(path, newUploadName);
        System.out.println("存放路径：" +dir);
        // exists() 测试此抽象路径名表示的文件或目录是否存在。
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //MultipartFile自带的解析方法
        try {
//            FileCopyUtils.copy(multipartFile.getInputStream(), Files.newOutputStream(dir.toPath()));
            multipartFile.transferTo(dir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传成功";
    }

//    @RequestMapping("/pictureUpload2")
    @ResponseBody
    public String saveUpload2(MultipartFile multipartFile) throws IOException {
        //如果文件不存在上传失败
        if (multipartFile.isEmpty()) {
//            LOGGER.info("上传失败");
            System.out.println("文件不存在");
            return "upload fail";
        }
        //获取文件名字
        String fileName = multipartFile.getOriginalFilename();
        System.out.println(fileName);
        //设置编译后文件存在路径
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/pictureUpload/";
        //获取项目路径
        File directory = new File("src/main/resources/static/pictureUpload");
        String paths = directory.getCanonicalPath();

        File dest = new File(paths+'/' + fileName);
        System.out.println(dest.getAbsoluteFile());

        FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
        //以流的方式上传
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
        byte[] bs = new byte[1024];
        int len;
        while ((len = fileInputStream.read(bs)) != -1) {
            bos.write(bs, 0, len);
        }
        bos.flush();
        bos.close();
//        try {
//            //文件上传
//            multipartFile.transferTo(dest);
//            LOGGER.info("上传成功");
//            return "upload success";
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return "upload success";
    }

    @PostMapping("/pictureUpload3")
    @ApiOperation(value ="图片上传" )
    @ResponseBody
    public ResultVo saveUpload3(@RequestParam MultipartFile multipartFile) throws IOException {
        System.out.println("进入了上传图片！");
        ResultVo resultVo = new ResultVo();
        //如果文件不存在上传失败
        if (multipartFile.isEmpty()) {
//            LOGGER.info("上传失败");
            System.out.println("文件不存在");
            resultVo.setMsg("fail");
            return resultVo;
        }
        //获取文件名字
        String p="http://192.168.221.249:8081/file/getPic";
        String fileName = multipartFile.getOriginalFilename();
//        fileName.s
//        String newFile=p+File.separator+fileName;
        System.out.println(fileName);
//        //设置编译后文件存在路径
//        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/pictureUpload/";
//        //获取项目路径
        File directory = new File("src/main/resources/static");
        String paths = directory.getCanonicalPath();

//        File dest = new File(paths+'/' + fileName);
//        System.out.println(dest.getAbsoluteFile());
        String substring = paths.substring(0, 6);

        File file = new File(substring + File.separator + "imagesUpload");
        if(!file.exists()){
            file.mkdirs();
        }
        String s = file + File.separator + fileName;
        FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
        //以流的方式上传
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(s));
        byte[] bs = new byte[1024];
        int len;
        while ((len = fileInputStream.read(bs)) != -1) {
            bos.write(bs, 0, len);
        }
        bos.flush();
        bos.close();
//        try {
//            //文件上传
//            multipartFile.transferTo(dest);
//            LOGGER.info("上传成功");
//            return "upload success";
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        List list = new ArrayList();
        list.add(p+"/"+fileName);
        list.add(substring + File.separator + "imagesUpload");
        list.add(s);
        resultVo.setData(list);
        return resultVo;
    }

    @GetMapping("/getPic/{pic}")
    public ResponseEntity<byte[]> getImg(@PathVariable("pic") String pic) throws IOException {
//        File directory = new File("src/main/resources/static");
//        String paths = directory.getCanonicalPath();
//        String substring = paths.substring(0, 6);
//        String file = substring + File.separator + "imagesUpload";
        //通过自己写的http工具类获取到图片输入流
        //    服务器的地址:/atest/pictrueUpload
        InputStream inputStream = new FileInputStream(new File("D:\\saa\\imagesUpload" + File.separator + pic));
        //将输入流转为byte[]
        byte[] bytesByStream = getBytesByStream(inputStream);
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);

        return new ResponseEntity<>(bytesByStream,headers, HttpStatus.OK);
    }
    public byte[]  getBytesByStream(InputStream inputStream){
        byte[] bytes = new byte[1024];

        int b;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            while((b = inputStream.read(bytes)) != -1){

                byteArrayOutputStream.write(bytes,0,b);
            }
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


}
